package com.tarena.lbs.business.servcie.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.param.PicUpdateParam;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.model.Result;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.business.dao.mapper.StoreMapper;
import com.tarena.lbs.business.dao.repository.StoreRepository;
import com.tarena.lbs.business.pojo.param.StoreParam;
import com.tarena.lbs.business.pojo.po.BusinessPO;
import com.tarena.lbs.business.pojo.po.StorePO;
import com.tarena.lbs.business.pojo.query.AreaStoreQuery;
import com.tarena.lbs.business.pojo.query.BusinessQuery;
import com.tarena.lbs.business.pojo.query.StoreQuery;
import com.tarena.lbs.business.pojo.vo.StoreVO;
import com.tarena.lbs.business.servcie.StoreService;
import com.tarena.lbs.common.enums.Roles;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class StoreServiceImpl implements StoreService {

    @Autowired
    private StoreRepository storeRepository; // 注入StoreMapper用于数据库操作
    @DubboReference
    private AttachApi attachApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UserApi userApi;



    @Override

    public Result<Void> insertStore(StoreParam param) {

        StorePO storePO = new StorePO();
        BeanUtils.copyProperties(param, storePO);
        storePO.setCreateTime(new Date());
        storePO.setUpdateTime(new Date());
        storePO.setStoreLogo("暂无");
        // ========== 1. 检查用户登录状态 ==========
        UserPrinciple currentUser = null;
        try {
            currentUser = UserPrinciple.getCurrentUser();
        } catch (BusinessException e) {
            return Result.fail("1" ,"用户未登录");
        }

        // ========== 2. 检查用户角色（必须为商家角色） ==========
        if (currentUser.getRole() != Roles.SHOP) {
            return Result.fail("2" ,"用户角色错误");
        }

        // ========== 3. 检查商家是否存在（通过入参businessId） ==========
        Integer businessId = param.getBusinessId();
        if (businessId == null) {
            return Result.fail("3" ,"商家ID不能为空");
        }
        BusinessPO businessDO = storeRepository.selectBusinessById(businessId);
        if (businessDO == null) {
            return Result.fail("4" ,"商家不存在");
        }
        storeRepository.insertStore(storePO);
        Integer storeId = storePO.getId();
        if (storeId == null) {
            return Result.fail("5" ,"插入数据失败");
        }
        // ========== 5. 保存到 RedisGEO（用于位置计算） ==========
//        Boolean redisGeoEnable = redisTemplate.opsForValue().getBit(1, 1);
//        if (redisGeoEnable != null && redisGeoEnable) {
//            // 验证经纬度有效性
//            try {
//                double longitude = Double.parseDouble(storePO.getStoreLongitude());
//                double latitude = Double.parseDouble(storePO.getStoreLatitude());
//                Point point = new Point((int) (longitude * 1000000), (int) (latitude * 1000000));
//                redisTemplate.opsForGeo().add("store:geo", point, storeId.toString());
//            } catch (NumberFormatException e) {
//                return Result.fail("6" ,"经纬度格式错误");
//            }
//        }
        // ========== 6. 绑定图片（调用附件服务） ==========
//        if (param.getStoreImagesIds() != null && !param.getStoreImagesIds().isEmpty()) {
//            List<PicUpdateParam> updateParams = param.getStoreImagesIds().stream()
//                    .map(picId -> {
//                        PicUpdateParam picParam = new PicUpdateParam();
//                        picParam.setBusinessId(storeId);
//                        picParam.setBusinessType(1);
////                        picParam.setAttachId(picId);
//                        return picParam;
//                    })
//                    .collect(Collectors.toList());
//            attachApi.batchUpdateBusiness(updateParams);
//        }
        return Result.success();
    }

    @Override
    public Result<PageResult<StoreVO>> getAllstore(StoreQuery query) {
        log.info("66666查询店铺信息：{}", query);
        // 1. 检查用户登录状态
        UserPrinciple currentUser;
        try {
            currentUser = UserPrinciple.getCurrentUser();
        } catch (BusinessException e) {
            return Result.fail("1", "用户未登录，无法查询店铺列表");
        }

        // 2. 检查用户角色是否为商家角色（Roles.SHOP）
        if (currentUser.getRole() != Roles.SHOP) {
            return Result.fail("2", "仅商家角色有权限查询店铺列表");
        }

        // 3. 调用用户服务获取商家账号信息
        AdminDto adminDto = userApi.getAdminById(currentUser.getId());
//            AdminDto adminDto = userApi.getAdminById(2);
        if (adminDto == null) {
            return Result.fail("3", "商家账号信息不存在，请检查账号关联");
        }

        // 4. 设置查询条件：商家ID
        // query.setBusinessId(adminDto.getBusinessId());

        // 5. 分页查询店铺数据（使用PageHelper实现分页）
        // PageHelper.startPage(query.getPageNo(), query.getPageSize());
        log.info("查询店铺信息：{}", query);
        List<StorePO> storePOList = storeRepository.selectByQuery(adminDto.getBusinessId());


        // 6. PO 转换为 VO
        List<StoreVO> storeVOList = storePOList.stream().map(po -> {
            StoreVO vo = new StoreVO();
            BeanUtils.copyProperties(po, vo);
            return vo;
        }).collect(Collectors.toList());

        // 7. 封装分页结果
        PageInfo<StorePO> pageInfo = new PageInfo<>(storePOList);
        PageResult<StoreVO> pageResult = new PageResult<>();
        pageResult.setTotal(pageInfo.getTotal());
        pageResult.setPageNo(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setObjects(storeVOList);
        // 正确返回带 PageResult 数据的成功结果
        return new Result<>(pageResult);
    }

    @Override
    public Result<PageResult<StoreVO>> getStoreByCity(AreaStoreQuery query) {
//
//        // 1. 检查用户登录状态
//        UserPrinciple currentUser;
//        try {
//            currentUser = UserPrinciple.getCurrentUser();
//        } catch (BusinessException e) {
//            return Result.fail("1", "用户未登录，无法查询店铺列表");
//        }
//        Integer adminId = currentUser.getId();
//
//        // 2. 调用用户服务 UserApi 获取账号信息，得到商家id
//        AdminDto adminDto = userApi.getAdminById(adminId);
//        if (adminDto == null) {
//            return Result.fail("1002", "商家账号信息不存在");
//        }
//        Integer businessId = adminDto.getBusinessId();
//        if (businessId == null) {
//            return Result.fail("1003", "商家账号未关联有效商家");
//        }
//
//        // 3. 校验区域id列表（非空）
//        List<Long> areaIds = query.getCityIdList();
//        if (areaIds == null || areaIds.isEmpty()) {
//            return Result.fail("1004", "区域ID列表不能为空");
//        }
//
//        // 4. 分页查询（基于商家ID和区域ID列表）
//        PageHelper.startPage(query.getPageNo(), query.getPageSize());
        List<StorePO> storePOList = storeRepository.selectByBusinessAndAreas(query);
        PageInfo<StorePO> pageInfo = new PageInfo<>(storePOList);
//
        // 5. PO 转换为 VO（属性拷贝 + 按需处理）
        List<StoreVO> storeVOList = storePOList.stream()
                .map(po -> {
                    StoreVO vo = new StoreVO();
                    BeanUtils.copyProperties(po, vo);
                    // 若有特殊字段转换（如图片地址、状态枚举翻译），可在此补充
                    return vo;
                })
                .collect(Collectors.toList());
//
        // 6. 封装分页结果
        PageResult<StoreVO> pageResult1 = new PageResult<>();
        pageResult1.setPageNo(pageInfo.getPageNum());
        pageResult1.setPageSize(pageInfo.getPageSize());
        pageResult1.setTotal(pageInfo.getTotal());
        pageResult1.setObjects(storeVOList);

        return new Result<>(pageResult1);
    }

    @Override
    public Result<Void> deleteStore(Long id) {
        storeRepository.deleteStore(id);
        return  Result.success();
    }

    @Override
    public Result<StoreVO> selectStore(Long id) {
        StorePO storePO = storeRepository.selectStore(id);
        StoreVO storeVO = new StoreVO();
        BeanUtils.copyProperties(storePO, storeVO);
        Result<StoreVO> Result = new Result<>(storeVO);
        return Result;
    }

    @Override
    public Result<Void> updateStore(StoreParam param) {
        storeRepository.updateStore(param);
        return  Result.success();
    }

    @Override
    public Result<Void> enableStore(Long id) {
        storeRepository.enableStore(id);
        return  Result.success();
    }


}